<template>
    <div class="root_main_pro_table" id="root_main_pro_table">
        <set-table-header ref="tableHeaderModal" v-if="tableHeaderVisible"
            @closeTableHeaderModal='closeHeaderConfig'
            :this-table-header-data="noShowColumns" :this-table-name="tableName"
            :this-table-header-data-middel="showColumns"/>
        <customer-table :columnsData="storeColumns" :dataSource="showSource" ref='current_table'
            @showMenu='showMenuHandler' @tableClick='tableClickHandler' @selectChange='selectChangeHandler'>
            <template v-for="col in slotColumns" :slot="col.dataIndex" slot-scope="{ item, index }">
                <component :is="col.slotType" :key="`${col.dataIndex}-${item.id}`" :data='item'
                    :columnInfo='col' @update='updateListener($event,col.dataIndex,item)'
                    @showDeliver='showDeliverHandler($event)'/>
            </template>
            <span slot="customTitle" class="settingStyle">
                <a-popover>
                    <template slot="content">
                        <div class="table-header" @click="showHeaderConfig"><a-icon type="setting"/>表头设置</div>
                    </template>
                    <a-button style="border: none;padding: 0;background-color: rgb(250, 250, 250);">
                        <a-icon type="menu" style="font-size: 20px"/>
                    </a-button>
                </a-popover>
            </span>
            <div slot="filterDropdown" slot-scope="{ column }">
                <div class="filter-con">
                    <p class="title">筛选条件
                        <span class="clear" @click="clearSelect(column.dataIndex,column)">清空</span>
                    </p>
                    <p class="name">{{column.title}}选择</p>
                    <a-select ref='ref_sel' class="fliter-op" :value='column.defaultSel' mode='multiple' @change="saveFilterCondition($event,column.dataIndex)">
                        <a-select-option v-for="item in column.editInfo" :key='item.value' :value="item.value">
                            {{item.label}}
                        </a-select-option>
                    </a-select>
                </div>
            </div>
        </customer-table>
        <gantt v-model="showGanttFlag" v-show="showGanttFlag" ref='ref_gantt'
            :showData='showSource' @ganttChange='ganttChange'/>
        <clickMenu id="show_menu" v-show='showMenu' :showFlag='showMenu' :menuPositnTop='menuPositnTop' :menuPositnLeft='menuPositnLeft'
            :menuRecord='menuRecord' @closeMenu='closeMenuHandler' @update='updateListener(arguments[0],arguments[1],arguments[2])'/>
        <a-drawer title="交付物操作" :width="700" @close='showDeliverFlag = false'
            :visible="showDeliverFlag" :body-style="bodyStyle">
            <deliverContent ref='ref_deliver_drawer' :deliverCols='deliverCols' :isAction='true'
                @update='updateListener(arguments[0],arguments[1],arguments[2])'/>
            <div class="btn-content">
                <a-button :style="{ marginRight: '8px' }" type="primary" @click="submitUpdate(false)">
                    应用
                </a-button>
                <a-button @click="submitUpdate(true)">
                    确定
                </a-button>
            </div>
        </a-drawer>
    </div>
</template>
<script>
import customerTable from '@/components/customer-table'
import deliverContent from '@/views/singleProject/projectPlan/components/deliver'
import clickMenu from '@/components/clickMenu'
import gantt from '@/components/gantt'
import completetxt from './components/columns/completetxt'
import dropdown from './components/columns/dropdown'
import date from './components/columns/date'
import tree from './components/columns/tree'
import day from './components/columns/day'
import icon from './components/columns/icon'
import classspan from './components/columns/classspan'
import deliver from './components/columns/deliver'
import setTableHeader from '@/components/setTableHeader/index'
import { timeFormat } from '@/utils/util.js'
import { mapMutations, mapGetters } from 'vuex'
import { exportList } from "@/api/projectManage.js";
import { saveFile } from '@/utils/util'
export default {
    props: {
        tableName: {
            type: String,
            default: ''
        },
        projectTeamUsers: {
          type: Object,
          default: () => {}
        },
        resourceOptsKey: {
          type: Object,
          default: () => {}
        }
    },
    inject: ['setMinMaxDate','mathWorkTime'],
    components: {
        date,
        dropdown,
        tree,
        gantt,
        clickMenu,
        day,
        completetxt,
        icon,
        setTableHeader,
        classspan,
        deliver,
        deliverContent,
        customerTable
    },
    computed: {
        ...mapGetters({
            isAddNode: 'isAddNode',
            showSource: 'getPlanTable',
            getSlotColumns: 'getSlotColumns',
            getStoreColumns: 'getPlanColumns',
            defaultColumns: 'getDefaultPlanColumns',
            resizeInfo: 'getResizeInfo',
            getAllTable: 'getAllTable',
            getKeyNodeNames: 'getKeyNodeNames'
        }),
        showColumns() {
            return this.$store.state.planTable.showColOfHeaderConfig
        },
        noShowColumns() {
            return this.$store.state.planTable.noShowColOfHeaderConfig
        },
        bodyStyle() {
            return { padding: '0px 20px 80px 20px' }
        },
    },
    watch: {
        //当表头数据或者展示的表头发生变化时重新赋值
        showColumns: {
            handler (n) {
                //列头
                this.storeColumns = this.getStoreColumns(n)
                //自定义控件
                this.slotColumns = this.getSlotColumns(this.storeColumns);
            },
            deep: true
        },
        //所有表头
        defaultColumns: {
            handler (n) {
                //列头
                this.storeColumns = this.getStoreColumns(this.showColumns)
                //自定义控件
                this.slotColumns = this.getSlotColumns(this.storeColumns);
            },
            deep: true
        }
    },
    data() {
        return {
            menuIndex: -1,
            deliverCols: [
                {
                    title: "交付物要求",
                    dataIndex: 'name', 
                    slotType: 'showspan',
                    width: 220,
                    scopedSlots: {
                        customRender: 'name'
                    }
                },
                {
                    title: "交付物",
                    dataIndex: 'subjectName', 
                    slotType: 'upload',
                    scopedSlots: {
                        customRender: 'subjectName'
                    }
                },
                {
                    title: "交付物状态",
                    dataIndex: 'subjectState',
                    width: 120,
                }
            ],
            showDeliverFlag: false,
            slotColumns: [],
            storeColumns: [],
            tableHeaderVisible: false,
            selValue: '',
            showMenu: false,
            menuPositnLeft: 0,
            menuPositnTop: 0,
            menuRecord: null,
            dateFormat: 'YYYY-MM-DD',
            showGanttFlag: false,
            tempTreeMap: new Map(),
            tempDefaultList: [],
            beforUpdateData: [],
            filterMap: new Map(),
            clickMethod: null,
            mouseupMethods: null,
            mousemoveMethods: null
        }
    },
    mounted() {
        //表格点击事件用于取消右键菜单和添加节点状态
        this.clickMethod = document.body.addEventListener('click',(ev) => {
            if(this.$store.state.planTable.stopPropagation) {
                this.$store.state.planTable.stopPropagation = false;
                return
            }
            if(this.showMenu) {
                this.showMenu = false;
                let preClickNode = document.querySelector('#scroll_content ul.main-content > li.click-row');
                preClickNode != null && (preClickNode.className = 'task-row')
                let preFixClickNode = document.querySelector('#fixed_content ul.main-content > li.click-row');
                preFixClickNode != null && (preFixClickNode.className = 'task-row')
            }
            this.showSource.forEach(ele => {
                if(ele.addNode != undefined && ele.addNode) {
                    ele.addNode = false
                    this.setRowOfPlanTable(ele)
                }
            })
        })
        //鼠标放开事件，用于调整表头
        this.mouseupMethods = document.body.addEventListener('mouseup',(ev) => {
            if (this.resizeInfo.key != undefined && this.resizeInfo.key != '') {
                let addWidth = ev.clientX - this.resizeInfo.x
                const newWidth = this.resizeInfo.width + addWidth;
                this.$store.state.planTable.defaultColumns.find(item => item.dataIndex == this.resizeInfo.key).style.width = `${newWidth}px`
            }
            this.setResizeInfo({})
        });
        this.mousemoveMethods = document.body.addEventListener('mousemove',(ev) => {
            if (this.resizeInfo.key != undefined && this.resizeInfo.key != '') {
                let addWidth = ev.clientX - this.resizeInfo.x
                const newWidth = this.resizeInfo.width + addWidth;
                this.$store.state.planTable.defaultColumns.find(item => item.dataIndex == this.resizeInfo.key).style.width = `${newWidth}px`
            }
        });
    },
    beforeDestroy() {
        document.body.removeEventListener('click',this.clickMethod)
        document.body.removeEventListener('click',this.mouseupMethods)
    },
    methods: {
        ...mapMutations(['setRowOfPlanTable','setPlanTable','setResizeInfo']),
        closeMenuHandler() {
            this.showMenu = false
            let preClickNode = document.querySelector('#scroll_content ul.main-content > li.click-row');
            preClickNode != null && (preClickNode.className = 'task-row')
            let preFixClickNode = document.querySelector('#fixed_content ul.main-content > li.click-row');
            preFixClickNode != null && (preFixClickNode.className = 'task-row')
        },
        //展开二级 或者 所有目录
        setExpandedRowKeys(expandAllFlag) {
            this.$store.state.planTable.loadNodeId = null
            this.setPlanTable(expandAllFlag);
        },
        // 全局搜索
        onSearch(val) {
            this.$store.state.planTable.filterMap.set('name',val)
            this.$nextTick(() => {
                this.$store.state.planTable.loadNodeId = null
                this.setPlanTable(true);
            })
        },
        exportBtn() {
          let arr = []
          this.$store.state.planTable.defaultColumns.map((item, index) => {
            if (item.dataIndex !== 'setting') {
              arr.push({
                name: item.name,
                title: item.displayName,
                num: index + 1
              })
            }
          })
          let columnsKeyData = {}
          let otherColumnsData = []
          let fixedColumns = ['lineNumber', 'taskCode', 'name', 'targetStartDate', 'targetEndDate', 'deliverable', 'resource', 'reviewerReference']
          arr.forEach(item => {
            if (fixedColumns.includes(item.name)) {
              columnsKeyData[item.name] = item
            } else if (item.name) {
              otherColumnsData.push(item)
            }
          })
          let columnsData = []
          columnsData = [columnsKeyData['lineNumber'], columnsKeyData['taskCode'], columnsKeyData['name'], columnsKeyData['targetStartDate'],
          columnsKeyData['targetEndDate'], columnsKeyData['deliverable'], columnsKeyData['resource'], columnsKeyData['reviewerReference'], ...otherColumnsData]
          let plannableStatus = this.$store.state.planTable.allConfig.enumerateLocalList.plannableStatus
          let exportData = JSON.parse(JSON.stringify(this.$store.state.planTable.planTable))
          let res = exportData.map(item => {
            item.reviewerReference = this.projectTeamUsers[item.reviewerReference] || ''
            item.editorReference = this.projectTeamUsers[item.editorReference] || ''
            item.resource = this.resourceOptsKey[item.resource] || ''
            item.plannableStatus = plannableStatus[item.plannableStatus] || ''
            item.deliverable = item.deliverable ? item.deliverable.map(item1 => item1.deliverableName).join(',') : ''
            return item
          })
          let data = {
            "titles" : columnsData,
            "projects": res
          }
          exportList(data).then(res1 => {
            if (res1 && res1.status === 200) {
              const blob = new Blob([res1.data], {type: 'application/octet-stream'})
              saveFile(blob, '项目计划.xlsx')
            } else {
              this.$message.warn('导出异常')
            }
          })
        },
        //展示交付物
        showDeliverHandler(row) {
            if (this.isAddNode(row.oid)) {
                this.$message.error('新增任务需保存后,才能进行交付物操作!')
                return;
            }
            this.showDeliverFlag = true;
            this.$nextTick(() => {
                this.$refs.ref_deliver_drawer.getDetails(row)
            })
        },
        submitUpdate(close) {
            this.$refs.ref_deliver_drawer.submitData(() => close && (this.showDeliverFlag = false));
        },
        showHeaderConfig() {
            this.tableHeaderVisible = true
        },
        closeHeaderConfig(newColumns = null) {
            this.tableHeaderVisible = false
            if (newColumns) {
                let showCols = newColumns.length == 0 ? [] : newColumns.split(',')
                this.$store.state.planTable.showColOfHeaderConfig = showCols
            }
        },
        //清空筛选条件
        clearSelect(key,col) {
            const self = this;
            //筛选器的默认选择
            self.$store.state.planTable.columns[self.$store.state.planTable.columns.findIndex(item => item.dataIndex == key)].defaultSel = []
            self.$store.state.planTable.filterMap.delete(key)
            self.$nextTick(() => {
                self.$store.state.planTable.loadNodeId = null
                self.setPlanTable(true);
            })
        },
        //保存筛选条件
        saveFilterCondition(value,key) {
            const self = this;
            //筛选器的默认选择
            self.$store.state.planTable.columns[self.$store.state.planTable.columns.findIndex(item => item.dataIndex == key)].defaultSel = value
            self.$store.state.planTable.filterMap.set(key,value)
            self.$nextTick(() => {
                self.$store.state.planTable.loadNodeId = null
                self.setPlanTable(true);
            })
        },
        selectChangeHandler(selectItem) {
            this.$store.state.planTable.hasSelectData = selectItem
            this.$emit('onSelectChange', selectItem)
        },
        showGanttView() {
            this.$refs.ref_gantt.refreshGantt();
            this.showGanttFlag = true;
        },
        ganttChange(data) {
            this.updateListener(data.start.value, data.start.key, data.start.task)
            this.updateListener(data.end.value, data.end.key, data.end.task)
            this.$nextTick(() => {
                this.$refs.ref_gantt.refreshGantt();
            })
        },
        //列表值修改
        updateListener(value,key,record) {
            let target = this.showSource.find(item => item.id == record.id)
            if (target) {
                //如果名称修改了
                if (key == 'name') {
                    if (this.getKeyNodeNames != undefined && this.getKeyNodeNames.includes(value))
                        target.KeyNode = '是'
                    else
                        target.KeyNode = ''
                }
                if (key == 'targetDuration.millis'){
                    let endDay = new Date(target.targetEndDate);
                    endDay.setDate(endDay.getDate() + (value - target[key]))
                    target.targetEndDate = timeFormat(endDay,this.dateFormat)
                }
                target[key] = value
                //如果其实时间大于结束时间，则重新计算结束时间
                if (key == 'targetStartDate') {
                    let start = new Date(target.targetStartDate)
                    let end = new Date(target.targetEndDate)
                    if (start > end) {
                        start.setDate(start.getDate() + (target['targetDuration.millis'] - 1))
                        target.targetEndDate = timeFormat(start,this.dateFormat)
                    }
                }
                //对节点的时间处理完成之后，对父节点处理
                if (key == 'targetStartDate' || key == 'targetEndDate' || key == 'targetDuration.millis') {
                    this.mathWorkTime(target,target.targetStartDate,target.targetEndDate);
                }
                this.setRowOfPlanTable(target)
                if (key == 'targetStartDate' || key == 'targetEndDate' || key == 'targetDuration.millis') {
                    this.setMinMaxDate(target,this.getAllTable(),true,true)
                }
                this.$emit('tableUpdated')
            }
        },
        //展示点击菜单
        showMenuHandler(e) {
            const self = this;
            //得到点击元素的父元素li
            const id = e.path.find(ele => ele.className != undefined && ele.className.indexOf('task-row') != -1 && ele.localName == 'li').id
            if (id != undefined && id != ''){
                self.showMenu = true
                self.menuRecord = self.showSource.find(item => item.id == id)
                self.menuIndex = self.showSource.findIndex(item => item.id == id)
                //给点击节点设置点击样式且取消前一个
                let preClickNode = document.querySelector('#scroll_content ul.main-content > li.click-row');
                preClickNode != null && (preClickNode.className = 'task-row')
                
                let preFixClickNode = document.querySelector('#fixed_content ul.main-content > li.click-row');
                preFixClickNode != null && (preFixClickNode.className = 'task-row')
                document.querySelectorAll('#scroll_content ul.main-content > li.task-row')[self.menuIndex].className += ' click-row'
                document.querySelectorAll('#fixed_content ul.main-content > li.task-row')[self.menuIndex].className += ' click-row'
                //设置弹出框坐标
                self.$nextTick(() => {
                    const menuHeight = document.getElementsByClassName('menu-content')[0].clientHeight
                    const tableHeigh = document.getElementById('root_main_pro_table').clientHeight
                    const clickY = e.clientY - document.getElementById('root_main_pro_table').getBoundingClientRect().top
                    self.menuPositnTop = (clickY + menuHeight) > tableHeigh ? tableHeigh - menuHeight :clickY
                    self.menuPositnLeft = e.clientX - document.getElementById('root_main_pro_table').getBoundingClientRect().left
                });
            }
        },
        //表格点击(当状态为添加任务时,点击添加任务行阻止冒泡)
        tableClickHandler(e) {
            const taskRow = e.path.find(ele => ele.className != undefined && ele.className.toString().indexOf('task-row') != -1 && ele.localName == 'li')
            //得到点击元素的父元素li
            if (taskRow == null || typeof(taskRow) == 'undefined')
                return
            const id = taskRow.id
            if (id != undefined && id != '') {
                const currentRow = this.showSource.find(item => item.id == id)
                if(currentRow.addNode != undefined && currentRow.addNode)
                    e.stopPropagation();
            }
        }
    }
}
</script>
<style scoped lang="less">
// /deep/ .checkColors{
//   background-color: #f0f7ff;
// }
.btn-content {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e9e9e9;
  padding: 10px 16px;
  background: #fff;
  text-align: right;
  z-index: 1;
}
.btn-save {
    margin-right: 10px;
}
#root_main_pro_table {
    height: 100%;
    background-color: #fff;
    position: relative;
    padding: 0px 30px 0 30px;
    /deep/ .click-row>p, /deep/ .move-row>p{
        // background-color: #cae7f9;
        background-color: #f0f7ff;
    }
    /deep/ .ant-table-row-cell-break-word {
        position: relative
    }
    /deep/ .update-data:before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        width: 8px;
        height: 8px;
        background: linear-gradient(-45deg,transparent 50%,red 50%);
    }
}
.icon_opt {
    position: absolute;
    top: 15px;
    right: 30px;
    z-index: 9;
}
.filter-con {
    width: 260px;
    text-align: left;
    overflow: hidden;
    .title {
        font-size: 14px;
        color: #999999;
    }
    .clear{
        font-size: 12px;
        color: #386bd7;
        cursor: pointer;
        float: right
    }
    .name {
        color: #333333;
        font-size: 14px;
        margin: 4px 0
    }
    .fliter-op {
        width: 100%;
    }
    .btn-sure {
        width: 60px;
        line-height: 30px;
        height: 30px;
        font-size: 13px;
        float: right;
        margin-top: 10px;
    }
}
.table-header{
  cursor: pointer;
  min-width: 78px;
  &:nth-of-type(1) {
    // margin-bottom: 8px;
  }
  &:hover{
    color: #386bd7;
  }
  .anticon{
    font-size: 14px;
    margin-right: 8px;
  }
}
</style>